﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Diagnostics;
using SMS;

namespace call2sms
{
    class SMSSender
    {
        private PDUEncoder encoder= new PDUEncoder();
        private GSMPort Port;
        private string SMSC;
        
        public String TargetNumber
        {
            get;
            set;
        }


        public SMSSender(String com)
        {
            Port = new GSMPort(com);
            Port.Init();
        }

        public SMSSender(GSMPort port)
        {
            Port = port;
        }

        ~SMSSender()
        {
           // Port.Close();
        }

        public void Init()
        {
            //get sms center number
            String echo = Port.ExecCommand("AT+CSCA?", 300, "error get smsc");
            //+CSCA: "+861333333333",145
            Match match = Regex.Match(echo,"\\+CSCA:\\s*\"\\+([0-9]+)\",.*");
            if(match.Success){
                SMSC = match.Groups[1].Value;
            }else{
                Debug.Write("can not get SMSC\n");
                return;
            }

            //set PDU mode
            echo = Port.ExecCommand("AT+CMGF=0",300,"error set PDU mode");
            if(echo.IndexOf("OK") >=0){
            }else{
                Debug.Write("PDU mode failed\n");
            }

            //some  use HEX instead of UCS2,so should do a check
            //echo = Port.ExecCommand("AT+CSCS=\"UCS2\"",300,"error set UCS2 mode");
            echo = Port.ExecCommand("AT+CSCS=\"HEX\"", 300, "error set UCS2 mode");


             if(echo.IndexOf("OK") >=0){
            }else{
                Debug.Write("UCS2 mode failed\n");
            }
            
        }


        public bool SendSMS(string msg)
        {
            
           string pdu = encoder.encodeSMS(SMSC,TargetNumber,msg);

           string echo = Port.ExecCommand("AT+CMGS="+encoder.nLength+"\n"+pdu+(char)26,500,"error send sms");
          // string echo = Port.ExecCommand("AT+CMGS?", 500, "error send sms");

           if (echo.IndexOf("OK") >= 0)

               return true;
           else
           {
               Debug.Write(echo);
               return false;
           }
        }
    }
}
